
﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Threading;

namespace WPFYanChatServer
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {

        protected override void OnStartup(StartupEventArgs e)
        {
            try
            {
                //当前运行WPF程序的进程实例
                Process process = Process.GetCurrentProcess();
                //遍历WPF程序的同名进程组
                foreach (Process p in Process.GetProcessesByName(process.ProcessName))
                {
                    //不是同一进程并且本进程启动时间最晚,则关闭较早进程
                    if (p.Id != process.Id && (p.StartTime - process.StartTime).TotalMilliseconds <= 0)
                    {
                        p.Kill();//这个地方用kill 而不用Shutdown();的原因是,Shutdown关闭程序在进程管理器里进程的释放有延迟不是马上关闭进程的
                        //Application.Current.Shutdown();
                        return;
                    }
                }
                base.OnStartup(e);
            }
            catch (Exception ex)
            {

                MessageBox.Show("OnStartup" + ex.ToString());
            }

        }
        //全局异常时的事件
        void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendFormat("应用程序出现了未捕获的异常，{0}/n", e.Exception.Message);
            if (e.Exception.InnerException != null)
            {
                stringBuilder.AppendFormat("/n {0}", e.Exception.InnerException.Message);
            }
            stringBuilder.AppendFormat("/n {0}", e.Exception.StackTrace);
            ServerLog.writeLog("App_DispatcherUnhandledException" + stringBuilder.ToString() + DateTime.Now.ToString("yyyy-MM-dd"));

            Application.Current.Shutdown();
            System.Reflection.Assembly.GetEntryAssembly();
            string startpath = System.IO.Directory.GetCurrentDirectory();
            System.Diagnostics.Process.Start(startpath + "/xxxx.exe");

            e.Handled = true;
        
        }  
    }

}